//
//  SHDrawerViewController.swift
//  newShaohuoRen
//
//  Created by hujinbiao on 2018/3/21.
//  Copyright © 2018年 hujinbiao. All rights reserved.
//

import UIKit

class SHDrawerViewController: UIViewController {
    
    var navController : UINavigationController?
    
    /// 用户头像
    var headerImageView: UIImageView?
    /// 捎货人状态
    var shipperStatus: UILabel?
    /// 用户名
    var userNameLabel: UILabel?
    /// 手机号码
    var phoneNumberLabel: UILabel?
    /// 申请捎货人
    var applyShipperButton: UIButton?
    /// 优惠活动
    var campaignButton: UIButton?
    /// 用户等级
    var userlevelButton: UIButton?
    
    var tableView : UITableView?
    var dataArray = NSMutableArray()
    
    var images = ["icon_money_gray","icon_setting_gray"]
    
    var names = ["我的钱包","设置"]
    
    var headerImgStr : String?
    var nickNameStr : String?
    var nameStr : String?
    var accountStr : String?
    var mobileStr : String?
    
    var sexStr : String?
    var autographStr : String?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if UserTicketModel.sharedInstance.isLogin {
            //            requestBaseInfo()
            requestUserInfo()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        initTableView()
    }

    func initTableView() -> Void {
        
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 270, height: kScreenHeight))
        tableView?.dataSource = self
        tableView?.delegate = self
        tableView?.separatorStyle = .none
        tableView?.tableFooterView = UIView()
        view.addSubview(tableView!)
        
        setUserInfoHeaderView()
        
    }
    
    //用户基础信息
    func requestBaseInfo() -> Void {
        
        //要加密的数据
        let param = ["command":"baseInfo","uid":UserTicketModel.sharedInstance.uid,"token":UserTicketModel.sharedInstance.token,"app_name":"shr"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            
            let data = resultDict["data"] as! [String:AnyObject]
            let taking = "\(data["taking_status"]!)"
            if taking == "0"{
                UserTicketModel.sharedInstance.shipping_status = false
                self.shipperStatus?.isHidden = UserTicketModel.sharedInstance.shipping_status
            }else {
                UserTicketModel.sharedInstance.shipping_status = true
                self.shipperStatus?.isHidden = UserTicketModel.sharedInstance.shipping_status
            }
            
//            UserTicketModel.sharedInstance.user_type = data["user_status"] as? Int
//
        })
    }
    
    func requestUserInfo() -> Void {
        
        //要加密的数据
        let param = ["command":"userInfo","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","app_name":"shr"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"UserInfo"], successed: { (resultDict) in
            
            let data = resultDict["data"] as! [String:AnyObject]
            self.headerImgStr = "\(endpoint)/\(data["header_img"]!)"
            self.nickNameStr = "\(data["nick_name"]!)"
            self.nameStr = "\(data["real_name"]!)"
            self.accountStr = "\(data["mobile"]!)"
            self.mobileStr = "\(data["mobile"]!)"
            if data["sex"] as! String == "0"{
                self.sexStr = "保密"
            }else if data["sex"] as! String == "1" {
                self.sexStr = "男"
            }else{
                self.sexStr = "女"
            }
            self.autographStr = "\(data["signature"]!)"
            
            self.headerImageView?.sd_setImage(with: URL(string: self.headerImgStr!), placeholderImage: UIImage(named:"icon_default_header_bg"))
            self.userNameLabel?.text = self.mobileStr
            self.phoneNumberLabel?.text = self.nickNameStr
            
            //icon_vip_gold
            let type = data["type"] as? String
            if type=="0" {
                self.userlevelButton?.setTitle("普通用户", for: .normal)
            }else {
                self.userlevelButton?.setImage(UIImage(named: "icon_vip_gold"), for: .normal)
                self.userlevelButton?.setTitle("金卡会员", for: .normal)
            }
            
            let status = data["status"] as? String
            if status == "0"{
                self.shipperStatus?.isHidden = false
            }else {
                self.shipperStatus?.isHidden = true
            }
            
            
        })
    }
    
    //点击图像
    @objc func SELUserInfoButton() -> Void {
        let board = UIStoryboard(name: "InfoTableViewController", bundle: nil)
        let infoVc = board.instantiateInitialViewController() as! InfoTableViewController
        infoVc.headerImgStr = self.headerImgStr
        infoVc.nickNameStr = self.nickNameStr
        infoVc.nameStr = self.nameStr
        infoVc.accountStr = self.accountStr
        infoVc.mobileStr = self.mobileStr
        infoVc.sexStr = self.sexStr
        infoVc.autographStr = self.autographStr
        pushMainViewController(infoVc)

    }
    //会员等级
    @objc func SELUserLevelButton() -> Void {
        
    }
    
    /**
     菜单跳转
     
     - parameter targetViewController:
     */
    func pushMainViewController(_ targetViewController: UIViewController) -> Void {
        
        navController?.pushViewController(targetViewController, animated: true)
        slideMenuController()?.closeLeft()
    }
    
    /**
     设置用户信息视图
     */
    func setUserInfoHeaderView() {
        let tableViewHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 175))
        self.tableView?.tableHeaderView = tableViewHeaderView
        
        headerImageView = UIImageView(frame: CGRect(x: 16, y: 64, width: 80, height: 80))
        headerImageView?.image = UIImage(named: "icon_default_header_bg")
        tableViewHeaderView.addSubview(headerImageView!)
        headerImageView?.layer.cornerRadius = 40
        headerImageView?.layer.masksToBounds = true
        
        headerImageView?.isUserInteractionEnabled = true
        let tapGesutre = UITapGestureRecognizer(target: self, action: #selector(SELUserInfoButton))
        headerImageView?.addGestureRecognizer(tapGesutre)
        
        shipperStatus = UILabel(frame: CGRect(x: 0, y: 55, width: 80, height: 20))
        headerImageView?.addSubview(shipperStatus!)
        shipperStatus?.backgroundColor = UIColor(hexString: "515151").withAlphaComponent(0.9)
        shipperStatus?.textColor = UIColor.white
        shipperStatus?.font = UIFont.systemFont(ofSize: 10)
        shipperStatus?.textAlignment = NSTextAlignment.center
        shipperStatus?.text = "休息中"
        
        userNameLabel = UILabel(frame: CGRect(x: headerImageView!.frame.maxX+10, y: headerImageView!.frame.origin.y,
                                              width: view.bounds.width-40, height: 20))
        
        tableViewHeaderView.addSubview(userNameLabel!)
        userNameLabel?.font = UIFont.systemFont(ofSize: 17)
        userNameLabel?.textAlignment = NSTextAlignment.left
        userNameLabel?.textColor = UIColor(hexString: "333333")
        userNameLabel?.text = "未设置电话"
        //userNameLabel?.backgroundColor = UIColor.redColor()
        
        userNameLabel?.isUserInteractionEnabled = true
        let tapUserNameGesutre = UITapGestureRecognizer(target: self, action: #selector(SELUserInfoButton))
        userNameLabel?.addGestureRecognizer(tapUserNameGesutre)
        
        phoneNumberLabel = UILabel(frame: CGRect(x: headerImageView!.frame.maxX+10, y: userNameLabel!.frame.maxY+8,
                                                 width: view.bounds.width-40, height: 20))
        
        tableViewHeaderView.addSubview(phoneNumberLabel!)
        phoneNumberLabel?.font = UIFont.systemFont(ofSize: 15)
        phoneNumberLabel?.textAlignment = NSTextAlignment.left
        phoneNumberLabel?.textColor = UIColor(hexString: "9C9C9C")
        phoneNumberLabel?.text = "未设置姓名"
        //phoneNumberLabel?.backgroundColor = UIColor.redColor()
        
        phoneNumberLabel?.isUserInteractionEnabled = true
        let tapPhoneNumberGesutre = UITapGestureRecognizer(target: self, action: #selector(SELUserInfoButton))
        phoneNumberLabel?.addGestureRecognizer(tapPhoneNumberGesutre)
        
        userlevelButton = UIButton(type: UIButtonType.custom)
        userlevelButton?.backgroundColor = UIColor.red
        userlevelButton?.frame = CGRect(x: headerImageView!.frame.maxX+10, y: phoneNumberLabel!.frame.maxY+8, width: 100, height: 25)
        userlevelButton?.setTitle("普通用户", for: UIControlState())
        tableViewHeaderView.addSubview(userlevelButton!)
        userlevelButton?.setTitleColor(UIColor(hexString: "646464"), for: UIControlState())
        userlevelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        userlevelButton?.backgroundColor = UIColor(hexString: "E7E7E7")
        userlevelButton?.layer.cornerRadius = 12.5
        userlevelButton?.layer.masksToBounds = true
        userlevelButton?.imageView?.contentMode = UIViewContentMode.scaleAspectFit
        userlevelButton?.imageEdgeInsets = UIEdgeInsets(top: 3, left: 0, bottom: 3, right: 0)

        userlevelButton?.addTarget(self, action: #selector(SELUserLevelButton),
                                   for: UIControlEvents.touchUpInside)
        
        let bottomLineView = UIView(frame: CGRect(x: 20, y: 174, width: view.bounds.width-40, height: 1))
        bottomLineView.backgroundColor = UIColor.clear
        tableViewHeaderView.addSubview(bottomLineView)
         bottomLineView.drawDashLine(withLineLength: 3, lineSpacing: 2, lineColor: UIColor(hexString: "DCDCDC"))
    }
}

extension SHDrawerViewController:UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellid")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cellid")
        }
        cell?.selectionStyle = .none
        cell?.textLabel?.textColor = UIColor.darkGray
        cell?.imageView?.image = UIImage(named: images[indexPath.row])
        cell?.textLabel?.text = names[indexPath.row]
        
        return cell!
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row==0 {
            let board = UIStoryboard(name: "BalanceViewController", bundle: nil)
            let Vc = board.instantiateInitialViewController() as! BalanceViewController
            pushMainViewController(Vc)
        }else if indexPath.row==1{
            let board = UIStoryboard(name: "SettingViewController", bundle: nil)
            let Vc = board.instantiateInitialViewController() as! SettingViewController
            pushMainViewController(Vc)
        }
    }
    
    
}
